//
//  ExportUserExcelPage.swift
//  ReportScan
//
//  Created by woniu on 2025/11/17.
//

import SwiftUI
import SwiftXLSX

class PhyUserItem {
    var no = ""
    var date = ""
    var name = ""
    var age = ""
    var gender = ""
    var phone = ""
    var idCard = ""
    var archives = ""
    var uploadState = ""
    //体检机构
    var insName = ""
    var address = ""
    //体检类型
    var peType = ""
    //接收时间
    var reDate = ""
}


struct ExportUserExcelPage: View {
    
    @State var pageIndex = 1
    @State var dataList:[PhyUserItem] = []
    @State var totalCount = 0
    @State var isStop = false
    
    var body: some View {
        Text("根据数据生成excel表格，并导出")
        VStack(alignment: .leading) {
            Button(role: .none) {
                genderExcel()
            } label: {
                Text("导出")
            }
            Button(role: .none) {
                self.onWillDown()
            } label: {
                Text("获取数据")
            }
            Button(role: .none) {
                isStop = true
            } label: {
                Text("暂停")
            }
            Button(role: .none) {
                isStop = false
                onWillDown()
            } label: {
                Text("继续")
            }
            
        }
        .padding()
        Spacer()
    }
    ///注入档案数据
    private func genderExcel() {
        
        var userList:[PhyUserItem] = self.dataList
        
        
        let excelBook = XWorkBook()
        
        func GetRandomFont() -> XFontName {
            let cases = XFontName.allCases
            return cases[Int.random(in: 0..<cases.count)]
        }
        let sheet = excelBook.NewSheet("档案列表")
        
        //体检编号
        let noCell = sheet.AddCell(XCoords(row: 1, col: 1))
        noCell.value = .text("体检编号")
        
        //体检日期
        let dateCell = sheet.AddCell(XCoords(row: 1, col: 2))
        dateCell.value = .text("体检日期")
        
        //姓名
        let nameCell = sheet.AddCell(XCoords(row: 1, col: 3))
        nameCell.value = .text("姓名")
        
        //年龄
        let ageCell = sheet.AddCell(XCoords(row: 1, col: 4))
        ageCell.value = .text("年龄")
        
        //性别
        let genderCell = sheet.AddCell(XCoords(row: 1, col: 5))
        genderCell.value = .text("性别")
        
        //电话
        let phoneCell = sheet.AddCell(XCoords(row: 1, col: 6))
        phoneCell.value = .text("电话")
        
        //证件号码
        let idCardCell = sheet.AddCell(XCoords(row: 1, col: 7))
        idCardCell.value = .text("证件号码")
        
        //公卫档案
        let archivesCell = sheet.AddCell(XCoords(row: 1, col: 8))
        archivesCell.value = .text("公卫档案")
        
        //公卫数据上传
        let uploadCell = sheet.AddCell(XCoords(row: 1, col: 9))
        uploadCell.value = .text("公卫数据上传")
        
        //家庭住址
        let addressCell = sheet.AddCell(XCoords(row: 1, col: 10))
        addressCell.value = .text("家庭住址")
        
        //体检类型
        let typeCell = sheet.AddCell(XCoords(row: 1, col: 11))
        typeCell.value = .text("体检类型")
        
        //机构
        let unitCell = sheet.AddCell(XCoords(row: 1, col: 12))
        unitCell.value = .text("体检机构")
        
        //数据接收时间
        let reDateCell = sheet.AddCell(XCoords(row: 1, col: 13))
        reDateCell.value = .text("数据接收时间")
        
       
        //内容
        for (index,user) in userList.enumerated(){
            let row = index + 2
            //体检编号
            let itemCell1 = sheet.AddCell(XCoords(row:row, col: 1))
            itemCell1.value = .text(user.no)
            
            //体检日期
            let itemCell2 = sheet.AddCell(XCoords(row:row, col: 2))
            itemCell2.value = .text(user.date)
            
            //姓名
            let itemCell3 = sheet.AddCell(XCoords(row:row, col: 3))
            itemCell3.value = .text(user.name)
            
            //年龄
            let itemCell4 = sheet.AddCell(XCoords(row:row, col: 4))
            itemCell4.value = .text(user.age)
            
            //性别
            let itemCell5 = sheet.AddCell(XCoords(row:row, col: 5))
            itemCell5.value = .text(user.gender)
            
            //电话
            let itemCell6 = sheet.AddCell(XCoords(row:row, col: 6))
            itemCell6.value = .text(user.phone)
            
            //证件号码
            let itemCell7 = sheet.AddCell(XCoords(row:row, col: 7))
            itemCell7.value = .text(user.idCard)
            
            //公卫档案
            let itemCell8 = sheet.AddCell(XCoords(row:row, col: 8))
            itemCell8.value = .text(user.archives)
            
            //公卫数据上传
            let itemCell9 = sheet.AddCell(XCoords(row:row, col: 9))
            itemCell9.value = .text(user.uploadState)
           
            //住址
            let itemCell10 = sheet.AddCell(XCoords(row:row, col: 10))
            itemCell10.value = .text(user.address)
            
            //体检类型
            let itemCell11 = sheet.AddCell(XCoords(row:row, col: 11))
            itemCell11.value = .text(user.peType)
            
            //机构
            let itemCell12 = sheet.AddCell(XCoords(row:row, col: 12))
            itemCell12.value = .text(user.insName)
            
            //数据接收时间
            let itemCell13 = sheet.AddCell(XCoords(row:row, col: 13))
            itemCell13.value = .text(user.reDate)
            
        }
        
        //导出
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy_MM_dd_HH:mm_ss"
        let fileName = "\(formatter.string(from: Date()))_档案数据.xlsx"
        let filePath = excelBook.save(fileName)
        print("===========>生成完成\(filePath)")
                let url = URL(fileURLWithPath: filePath)
                //自动打开该文档
                NSWorkspace.shared.open(url)
    }
    
    func onWillDown(){
        httpGetData(page: self.pageIndex)
    }
    
    
    func httpGetData(page:Int){
        print(">>>>>>>>>>>>>>>>>开始查询第\(page)页")
        HttServer.httpGetPhyUserList(pageIndex: page) { re, dataList,total in
            if re{
                
                DispatchQueue.main.async {
                    self.dataList.append(contentsOf: dataList)
                    self.totalCount += dataList.count
                   
                    print("第\(page)页 共\( self.totalCount)条")
                    //当数据量达到一定史，先生成，再继续查询接收
                    if self.totalCount >= 10000{
                        print("数据达到了\(self.totalCount)，成表格")
                        self.genderExcel()
                        self.totalCount = 0
                    }
                    
                    if dataList.isEmpty || self.totalCount >= total{
                        print("------------------批量查询结束，page:\(page)页 \(dataList.count)条")
                        self.genderExcel()
                        
                    }else{
                      
                        if self.isStop{
                            print("已暂停。。。。。。")
                            return
                        }
                        self.pageIndex = self.pageIndex + 1
                        if self.pageIndex < 22{
                            httpGetData(page: self.pageIndex)
                        }
                       
                    }
                }
            }else{
                print("第\(page)页报错了")
            }
        }
    }

   
}

#Preview {
    ExportUserExcelPage()
}
